package com.bupt.liutong.admin.groupon.bo;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Autowired;

import com.bupt.liutong.admin.core.base.CodeTableManager;
import com.bupt.liutong.admin.groupon.dao.UserDao;
import com.bupt.liutong.admin.groupon.dto.User;
import com.bupt.liutong.admin.groupon.form.UserForm;
import com.bupt.liutong.util.BeanUtils;
import com.bupt.liutong.util.StringUtils;

import net.sf.json.JSONObject;

public class CityBo {

	public static Map<String, String> cityNameReverse = CodeTableManager
			.getInstance().get("cityNameReverse");

	@Autowired
	public UserDao userDao;

	public void updateUser(UserForm userForm) {
		User user = new User();
		BeanUtils.copyProperties(user, userForm);
		userDao.updateUser(user);
	}
	
	public Integer getCityId(HttpServletRequest request, HttpServletResponse response){
		// uid is the baidu id of the visitor
		String uid = request.getParameter("bd_sig_user");
		String cityIdStr = request.getParameter("cityId");
		String ip = request.getRemoteAddr();
		Integer cityId = null;
		
		// cityId获取优先级，页面参数->数据库->cookie->查询ip对应城市->默认为全国
		if (!StringUtils.isEmpty(cityIdStr)) {
			cityId = Integer.parseInt(cityIdStr);
			// remove
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				for (Cookie cookie : cookies) {
					System.out.println(cookie.getName()+"="+cookie.getValue());
					if (cookie.getName().equalsIgnoreCase("baiducity")) {
						cookie.setMaxAge(0);
					}
				}
			}
			// add
			Cookie c = new Cookie("baiducity", cityId.toString());
			c.setMaxAge(60*60*24*365);
			response.addCookie(c);
		}
		if (cityId == null && uid != null) {
			cityId = this.getCityIdByUidAndIp(uid, ip);
			// remove
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				for (Cookie cookie : cookies) {
					System.out.println(cookie.getName()+"="+cookie.getValue());
					if (cookie.getName().equalsIgnoreCase("baiducity")) {
						cookie.setMaxAge(0);
					}
				}
			}
			// add
			Cookie c = new Cookie("baiducity", cityId.toString());
			c.setMaxAge(60*60*24*365);
			response.addCookie(c);
		}
		if (cityId == null) {
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				for (Cookie cookie : cookies) {
					System.out.println(cookie.getName()+"="+cookie.getValue());
					if (cookie.getName().equalsIgnoreCase("baiducity")) {
						// baiducity is the cityid of the visitor that restored
						// in cookie
						cityId = Integer.valueOf(cookie.getValue());
						break;
					}
				}
			}
		}
		if (cityId == null) {
			cityId = this.getCityIdByIp(ip);
			// remove
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				for (Cookie cookie : cookies) {
					System.out.println(cookie.getName()+"="+cookie.getValue());
					if (cookie.getName().equalsIgnoreCase("baiducity")) {
						cookie.setMaxAge(0);
					}
				}
			}
			// add
			Cookie c = new Cookie("baiducity", cityId.toString());
			c.setMaxAge(60*60*24*365);
			response.addCookie(c);
		}
		return cityId;
	}

	public Integer getCityIdByIp(String ip) {
		String url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip="
				+ ip;
		System.out.println(url);
		HttpClient httpClient = new DefaultHttpClient();
		try {
			String responseStr = httpClient.execute(new HttpGet(url),
					new BasicResponseHandler());
			if (!StringUtils.isEmpty(responseStr)) {
				String cityName = JSONObject.fromObject(responseStr)
						.get("city").toString();
				return Integer.parseInt(cityNameReverse.get(cityName));
			}
		} catch (Exception e) {
			// catch http exception & null pointer exception & integer format
			// exception, beacause we must return a certain value
			// e.printStackTrace();
			// throw new Exception("Unknown IP");
			System.err.println("error catching city information from ip " + ip);
		}
		return Integer.parseInt(cityNameReverse.get("全国"));
	}

	public Integer getCityIdByUidAndIp(String uid, String ip) {
		Integer cityId = userDao.getCityIdByUid(uid);
		if (cityId !=null) {
			return cityId;
		} else {
			cityId = getCityIdByIp(ip);
			User user = new User();
			user.setCityId(cityId);
			user.setUid(uid);
			userDao.insertUser(user);
			return cityId;
		}
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public static void main(String[] args) throws Exception {
		System.out.println(new CityBo().getCityIdByIp("60.28.9.50"));
	}
}
